﻿using System;
using System.Collections.Generic;
using System.Data;
using TravianAutoQueue.DomainModel.Entities;
using TravianAutoQueue.DataAccess.PersistentStorage;
using System.Reflection;

namespace TravianAutoQueue.DomainModel.Repositories
{
    public class BuildingRepository : IBuildingRepository
    {
        public IDataService Service { get; set; }

        public BuildingRepository()
        {
            //TODO: Add DAL Helper
            //Service = new DataService();
        }

        public T MapDataRowToEntity<T>(DataRow dataRow) where T : new()
        {
            if (dataRow == null)
                throw new ArgumentNullException("dataRow");

            var entityType = typeof(T);
            var properties = entityType.GetProperties();

            T entity = new T();
            foreach (PropertyInfo info in properties)
            {
                string colName = info.Name;
                if (!(dataRow[colName] is DBNull))
                    info.SetValue(entity, dataRow[colName], null);
            }

            return entity;
        }

        public IBuilding GetBuilding(int id)
        {
            var dt = Service.GetBuilding(id).Tables[0];
            var building = MapDataRowToEntity<Building>(dt.Rows[0]);
            return building;
        }

        public IBuilding GetBuildingByType(Enums.BuildingType type)
        {
            int id = Convert.ToInt32(type);
            var dt = Service.GetBuildingByType(id).Tables[0];
            var building = MapDataRowToEntity<Building>(dt.Rows[0]);
            return building;
        }
    }
}
